import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store/'
import Home from '@/components/home/'
import axios from "axios";

Vue.use(Router)

const routes = [
    {
        path: '/home',
        name: 'Home',
        component: Home,
        children: [
            {
                path: '/certificate',
                name:'Certificate',
                component: ()=>import('@/components/certificate/')
            },
            {
                path:'/setting',
                name:'Setting',
                component:()=>import('@/components/setting/')
            }
        ]
    },

    {
        path: '/login',
        name: 'Login',
        component: () => import('@/components/login/')
    }
]

const router = new Router({
    mode: 'history',
    base: "/",
    routes
})

router.beforeEach((to, from, next) => {
    let hasRoute = store.state.hasRoute

    const { user } = store.state
    let token
    if (user){
        token = user.token
    }

    if (to.path == '/login') {
        next()
    }else if (!token) {
        next({path: '/login'})

    } else if(token && !hasRoute) {
        axios.get("http://localhost:8080/sys/menu/nav", {
            headers: {
                token: user.token
            }
        }).then(res => {

            // 拿到menuList
            store.commit("setMenuList", res.data.data.nav)

            // 拿到用户权限
            store.commit("setPermList", res.data.data.authoritys)

            // 动态绑定路由
            let newRoutes = router.options.routes

            res.data.data.nav.forEach(menu => {
                if (menu.children) {
                    menu.children.forEach(e => {

                        // 转成路由
                        let route = menuToRoute(e)
                        // 把路由添加到路由管理中
                        if (route) {
                            newRoutes[0].children.push(route)
                        }

                    })
                }
            })

            router.addRoutes(newRoutes)

            hasRoute = true
            store.commit("changeRouteStatus", hasRoute)
        })
    }
    next()
})

// 导航转成路由
const menuToRoute = (menu) => {

    if (!menu.component) {
        return null
    }

    let route = {
        name: menu.name,
        path: menu.path,
        meta: {
            icon: menu.icon,
            title: menu.title
        }
    }
    route.component = () => import('@/components/' + menu.component +'/')
    return route
}

export default router